import { useState, useEffect } from "react"
import { Link, useParams } from "react-router-dom"
import { useSelector, useDispatch } from "react-redux"
import { Button, message, Modal, Tag, Space, Alert } from "antd"

import useCURD from "../../hooks/useCURD"
import * as apis from "../../apis/task"
import { formatFormItems } from "../../utils/formItems"
import CommonModalForm from "../../components/common/CommonModalForm"
import CommonTable, { createColumn } from "../../components/common/CommonTable"
import CommonFilterItem from "../../components/common/CommonFilterItem"
import { queryAppProcessesAction } from "../../store/actions/appDefAction"


const WorkflowTasks = () => {

  const dispatch = useDispatch()
  const curApp = useSelector(state => state.appDef.curApp)
  const processes = useSelector(state => state.appDef.processes)

  useEffect(() => {
    if (curApp.appDefinitionKey) {
      dispatch(queryAppProcessesAction(curApp.appDefinitionKey))
    }
  }, [curApp])

  const { state } = useParams()

  const getDefaultQueryByState = (state) => {
    switch (state) {
      case 'todo':
        return {
          assignment: 'assignee',
          state: 'open'
        }
      case 'claim':
        return {
          assignment: 'candidate',
          state: 'open'
        }
      case 'complete':
        return {
          assignment: 'involved',
          state: 'completed'
        }
    }
  }

  const {
    listData,
    loading,
    query,
    handleCancelForm,
    changeQueryValues,
    doQueryList,
    handleSubmit,
    formVisible,
    formTitle,
    formData
  } = useCURD({
    apis,
    moduleName: '任务',
    initQuery: false,
    defaultQuery: {
      appDefinitionKey: curApp.appDefinitionKey,
      ...getDefaultQueryByState(state)
    },
  })

  useEffect(() => {
    if (curApp.appDefinitionKey) {
      changeQueryValues({
        appDefinitionKey: curApp.appDefinitionKey
      })
    }
  }, [curApp])

  useEffect(() => {
    changeQueryValues({
      ...getDefaultQueryByState(state),
      processDefinitionId: undefined,
      text: undefined
    })
  }, [state])

  useEffect(() => {
    if (curApp.appDefinitionKey) {
      doQueryList()
    }
  }, [query])

  const handleFinishTask = (rowData) => {
    if (rowData.formKey) {
      apis.queryTaskForm(rowData.id).then(res => {
        const initValues = {}
        res.fields.forEach(el => {
          if (el.type === 'date' && el.value && el.value.split('-')[0].length !== 4) {
            initValues[el.id] = el.value.split('-').reverse().join('-')
          } else {
            initValues[el.id] = el.value
          }
        })
        setCompleleteForm({
          visible: true,
          formId: res.id,
          initValues: initValues,
          formItems: formatFormItems(res.fields),
          taskId: rowData.id
        })
      })
    } else {
      Modal.confirm({
        title: '确定要执行？',
        onOk: async () => {
          try {
            await apis.completeTask({
              id: rowData.id
            })
            message.success('任务执行成功')
            doQueryList()
          } catch (error) {
            message.error('任务执行失败')
          }
        }
      })
    }
  }

  const handleClaimTask = (rowData) => {
    Modal.confirm({
      title: '确定要认领？',
      onOk: async () => {
        try {
          await apis.claimTask(rowData.id)
          message.success('任务认领成功')
          doQueryList()
          // changeQueryValues({
          //   assignment: 'assignee',
          // })
        } catch (error) {
          message.error('任务认领失败')
        }
      }
    })
  }

  const handleSubmitCompleteForm = async (values) => {
    try {
      await apis.completeTaskForm({
        taskId: completeForm.taskId,
        formId: completeForm.formId,
        values
      })
      message.success('任务执行成功')
      setCompleleteForm({
        visible: false,
        formId: null,
        formItems: [],
        taskId: null
      })
      doQueryList()
    } catch (error) {
      message.error('任务执行失败')
    }
  }

  const columns = [
    {
      key: 'processDefinitionName',
      dataIndex: 'processDefinitionName',
      title: '流程',
      width: 200,
      render: (text, rowData) => {
        return text ?
          <Space>
            {text}
            <Tag color="blue">v{rowData.processDefinitionVersion}</Tag>
          </Space> :
          <span style={{ color: '#999' }}>无流程</span>
      }
    },
    createColumn.searchResult({
      dataIndex: 'name',
      title: '任务名称',
      searchWord: query.text
    }),
    createColumn.person({
      dataIndex: 'assignee',
      title: '执行人',
    }),
    createColumn.time({
      dataIndex: 'created',
      title: '分配时间',
    }),
    {
      key: 'action',
      title: '操作',
      width: 160,
      align: 'center',
      render: (rowData) => {
        return <Space>
          <Link to={`/workflow/tasks/${state}/detail/${rowData.id}`}>
            <Button
              size="small"
            >查看详情</Button>
          </Link>
          {
            (rowData.assignee && !rowData.endDate) &&
            <Button
              type="primary"
              size="small"
              onClick={() => {
                handleFinishTask(rowData)
              }}
            >完成</Button>
          }
          {
            (!rowData.assignee && !rowData.endDate) &&
            <Button
              type="primary"
              size="small"
              onClick={() => {
                handleClaimTask(rowData)
              }}
            >认领</Button>
          }
        </Space>
      }
    },
  ]

  const formItems = [
    {
      name: 'name',
      label: '任务名称'
    },
    {
      name: 'description',
      label: '描述'
    }
  ]

  const [completeForm, setCompleleteForm] = useState({
    visible: false,
    formItems: [],
    initValues: {},
    taskId: null,
    formId: null
  })

  return curApp?.appDefinitionKey ? <div className="page-wrap">
    <CommonModalForm
      title={formTitle}
      visible={formVisible}
      onCancel={handleCancelForm}
      onSubmit={handleSubmit}
      initValues={formData}
      formItems={formItems}
    ></CommonModalForm>
    <CommonModalForm
      title="执行任务"
      visible={completeForm.visible}
      initValues={completeForm.initValues}
      formItems={completeForm.formItems}
      onSubmit={handleSubmitCompleteForm}
      onCancel={() => {
        setCompleleteForm({
          visible: false,
          formId: null,
          formItems: [],
          taskId: null
        })
      }}
    ></CommonModalForm>
    <div className="page-head">
      <Space>
        <CommonFilterItem.Select
          label="流程"
          field="processDefinitionId"
          queryValues={query}
          onChangeQueryValues={changeQueryValues}
          options={processes.map(el => ({
            value: el.id,
            label: el.name + ' - v' + el.version
          }))}
        ></CommonFilterItem.Select>
      </Space>
      <Space>
        <CommonFilterItem.Search
          label="任务名称"
          field="text"
          queryValues={query}
          onChangeQueryValues={changeQueryValues}
        ></CommonFilterItem.Search>
      </Space>
    </div>
    <div className="page-body">
      <CommonTable
        dataSource={listData}
        columns={columns}
        loading={loading}
      ></CommonTable>
    </div>
  </div> :
    <div style={{ padding: 20 }}>
      <Alert
        message="对不起，您还没有选择应用"
        description="请先选择应用"
        type="warning"
        showIcon
      />
    </div>
}

export default WorkflowTasks